package com.kaili.basic.service.impl;

import javax.annotation.Resource;

import com.kaili.basic.service.BaseOperateLogService;
import com.kaili.common.aop.log.bean.OperateLogBean;
import com.kaili.common.util.CommonUtil;
import com.mongodb.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaseOperateLogServiceImpl implements BaseOperateLogService {

    @Resource
	private MongoTemplate mongoTemplate;

	public Page<OperateLogBean> getList(OperateLogBean logBean,String collectionName) {
		//设置分页起始数
		Integer pageSize = logBean.getPageSize();
		Integer start = (logBean.getPage()-1)*pageSize;

		BasicDBList condList = new BasicDBList();
		DBObject query = new BasicDBObject();

		if(StringUtils.isNotEmpty(logBean.getKey())){
			query.put("key", logBean.getKey());
			condList.add(query);
		}
		if(StringUtils.isNotEmpty(logBean.getCreateByName())){
			query.put("createByName", logBean.getCreateByName());
			condList.add(query);
		}
		if(null != logBean.getFunctionName()){
			query.put("functionName", logBean.getFunctionName());
			condList.add(query);
		}
		if(StringUtils.isNotEmpty(logBean.getSiteName())){
			query.put("siteName", logBean.getSiteName());
			condList.add(query);
		}
		if(null != logBean.getStartTime() && null != logBean.getEndTime()){
			query.put("createTime", (new BasicDBObject("$gte",logBean.getStartTime()).append("$lte",logBean.getEndTime())));
			condList.add(query);
		}

		DBObject condition= new BasicDBObject();
		condition.put("$and",condList);

		DBCursor cursor = mongoTemplate.getCollection(collectionName).find(condition)
				.sort(new BasicDBObject("createTime", 1)).skip(start).limit(pageSize);
		List<OperateLogBean> list = new ArrayList<OperateLogBean>();
		while(cursor.hasNext()){
			DBObject obj = cursor.next();
			OperateLogBean bean = new OperateLogBean();
			list.add(CommonUtil.dbObjectToBean(obj,bean));
		}

		Page<OperateLogBean> page = new Page<OperateLogBean>();
		page.setTotal(mongoTemplate.getCollection(collectionName).count(condition));
		page.setRecords(list);
		page.setSize(logBean.getPageSize());
		page.setCurrent(logBean.getPage());
		return page;
	}
}